<template>
  <div class="courseBag common-layout">
    <el-container class="container-box">
      <el-container class="courseBag-container">
        <!-- <el-header class="container-header">
                    <el-button @click="start" size="default" type="primary">刷新</el-button>
                </el-header> -->
        <el-main class="container-main" v-loading="loading">
          <el-scrollbar>
            <el-empty
              v-if="!myCourseCatebag.length"
              image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png"
            />
            <el-row :gutter="10" class="courseBag-container-cardBox">
              <el-col
                :lg="12"
                :md="24"
                class="card-box"
                v-for="(v, k) in myCourseCatebag"
                :key="k"
              >
                <el-card
                  class="card cursor-pointer height-100"
                  shadow="hover"
                  @click="toCourseList(v)"
                >
                  <div class="card-item">
                    <el-image
                      class="card-item-image"
                      :src="v.banner"
                      fit="contain"
                    />
                    <el-descriptions
                      class="card-descriptions"
                      :column="2"
                      :title="v.name"
                      extra=""
                      size="default"
                    >
                      <template #title>
                        {{ v.name }}
                      </template>
                      <el-descriptions-item :span="2" label="课程数量：">
                        <el-text size="default" type="info">
                          <!-- {{v.count}} 课时 -->
                          {{ v.packages?.length }} 课时
                        </el-text>
                      </el-descriptions-item>
                      <el-descriptions-item :span="2" label="课程介绍：">
                        <el-tooltip
                          disabled
                          effect="dark"
                          :content="v.info"
                          placement="top"
                        >
                          <el-text size="default" type="info" line-clamp="2">
                            {{ v.info }}
                          </el-text>
                        </el-tooltip>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-scrollbar>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  asyncSelectPackageCatebagRelation,
  asyncselectUsercourse,
  asyncselectteamcoursegroup,
} from "../../../api";
import { Storekey } from "../../../interface";
import Alymodel from "../../../mysql_interface/model";
import { courseCatebag } from "../../../sassMgmt/views/data/data";
import { getGroupedByCatebagArr } from "../../../util/cloudClass";
// 默认saas所有可公开的课包
const defaultPIDs = courseCatebag.map((e) => e.pID);

const prop = defineProps<{ myCourseIDs: number[] }>();
const emit = defineEmits(["update-course-ids"]);

const store = useStore(Storekey);
const route = useRoute();
const router = useRouter();
// 当前登录用户
const user = computed(() => {
  return store.state.user;
});
const teamId = computed(() => {
  return Number(user.value?.teamid);
});
// 监听团队切换
watch(
  () => teamId.value,
  (o, n) => {
    if (o !== n) start();
  }
);

onMounted(async () => {
  await start();
});
const loading = ref(false);
async function start() {
  if (!teamId.value) return;
  loading.value = true;
  // 成员-课程
  await getMyCourse();
  // 获取团队代理商课包
  const { rows, count } = await asyncselectteamcoursegroup({
    teamid: teamId.value,
  });
  // 没有查到就用前端默认的7个代理商课包
  const pIds = rows?.length
    ? rows.map((e) => Number(e.coursegroupid))
    : defaultPIDs;
  // 代理商课包-课程组
  await getPackageCatebagRelation(pIds);
  loading.value = false;
}

// 根据课程获取课程包
// 利用课程和课包-课程 求交集
const myCourseCatebag = computed(() => {
  let myCourse = myCourseMap.value[Number(user.value?.ID)] || [];
  return groupedByCatebagArr.value.filter((catebagItem) => {
    let packages = catebagItem.packages || [];
    for (let i = 0; i < packages.length; i++) {
      let c = packages[i];
      return myCourse.find((uc) => uc.course_ID === c.course_ID);
    }
  });
});

// 获取团队成员课程配置 user_ID - course_ID
const myCourseMap = ref<{ [uid: number]: Alymodel.IMusercourse[] }>({});
async function getMyCourse() {
  myCourseMap.value = await asyncselectUsercourse({
    teamid: teamId.value,
    user_ID: user.value?.ID,
    _order: "createtime",
  });
}
// 代理商课包-课程组关系
const groupedByCatebagArr = ref<Alymodel.GroupedByCatebag[]>([]);
// 获取指定代理商课包 =》 课程 =》 课程组 关系
const teamPackageCatebagRelation = ref<Alymodel.PackageCatebagRelation[]>([]);
async function getPackageCatebagRelation(pID: number[]) {
  const { rows: data, count } = await asyncSelectPackageCatebagRelation({
    ID: pID,
  });
  teamPackageCatebagRelation.value = data;
  // 按课程包分组
  groupedByCatebagArr.value = getGroupedByCatebagArr(data);
}

// 跳转
function toCourseList(row: Alymodel.GroupedByCatebag) {
  const courseIDs = row.packages.map((e) => Number(e?.course_ID));
  emit("update-course-ids", courseIDs);
  router.push({
    name: "课程列表",
    params: { ID: row.cID },
  });
}
</script>

<style scoped>
.container-box {
  /* 外边距 */
  --container-margin: 20px;
  --container-header-height: 7vh;
  --container-bg-color: #fff;
}

.courseBag-container {
  /* 控制高度 不用整个页面都有滚动条 方便查看右侧详情 */
  /* max-height: calc(100vh - 64px - 2 * var(--container-margin)); */
}

.container-header {
  background: var(--container-bg-color);
  width: 100%;
  padding: var(--container-margin) var(--container-margin) 10px;
}

.container-main {
  margin-top: var(--container-margin);
  padding: 0;
  /* !!! */
  /* overflow: hidden; */
  height: calc(100vh - 64px - 2 * var(--container-margin) - 47px - 47px);
}

@media screen and (max-width: 768px) {
  .container-main {
    height: auto;
    margin-bottom: 20px;
  }
}

.courseBag-container-cardBox {
  padding: 0 var(--container-margin);
  /* element UI一gutter设置为大于0时，el-row宽度溢出 */
  /* width: 100%; */
  /* display: flex;
    flex-wrap: wrap; */
  /* padding-right: 10px; */
}

.card-box {
  margin-top: 10px;
}

.card {
  min-width: 400px;
}

.card-item {
  display: flex;
}

.card-item-image {
  width: 240px;
  min-width: 240px;
  /* height: 158px;
    min-height: 158px; */
  overflow: visible;
}

.card-descriptions {
  margin-left: 10px;
}
</style>

<style>
#app.ojSass .courseBag .el-descriptions__title {
  width: 100%;
}

/* 隐藏横向滚动条无效 */
#app.ojSass .courseBag .container-main .el-scrollbar__wrap {
  overflow-x: hidden !important;
}

/* 设置横向滚动条宽高为0 */
#app.ojSass .courseBag .container-main .el-scrollbar__bar.is-horizontal {
  width: 0;
  height: 0;
}

#app.ojSass .courseBag .el-card__body {
  height: 100% !important;
  padding: 10px;
}

#app.ojSass .courseBag .el-descriptions__label:not(.is-bordered-label) {
  margin: 0;
}
</style>
